package cn.codeforfun.vote;

import cn.codeforfun.common.WechatService;
import cn.codeforfun.consts.RootConst;
import cn.codeforfun.consts.SessionConsts;
import cn.codeforfun.exchage.Exchange;
import cn.codeforfun.exchage.ExchangeDao;
import cn.codeforfun.follower.*;
import cn.codeforfun.material.Material;
import cn.codeforfun.material.MaterialService;
import cn.codeforfun.prize.Prize;
import cn.codeforfun.prize.PrizeService;
import cn.codeforfun.utils.FileUtils;
import cn.codeforfun.utils.Long2ShortUtil;
import cn.codeforfun.utils.RandomUtil;
import com.github.binarywang.utils.qrcode.QrcodeUtils;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpSession;
import javax.transaction.SystemException;
import javax.transaction.Transactional;
import java.io.File;
import java.util.*;

/**
 * Created by Administrator on 2017/2/15 0015.
 */
@Service
@Transactional
public class VoteService {
    @Autowired
    private VoteDao voteDao;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private MaterialService materialService;
    @Autowired
    private FollowerService followerService;
    @Autowired
    private ExchangeDao exchangeDao;
    @Autowired
    private RootConst rootConst;
    @Autowired
    private PrizeService prizeService;
    @Autowired
    private FollowerOptionDao followerOptionDao;

    public List<Vote> findAll() {
        List<Vote> all = voteDao.findVoteWithSubject();
        return all;
    }

    public boolean save(Vote vote) {
        voteDao.save(vote);
        for (Question question : vote.getQuestions()) {
            if (question.getVote() == null)
                question.setVote(vote);
            for (Option option : question.getOptions()) {
                if (option.getQuestion() == null)
                    option.setQuestion(question);
            }
        }
        voteDao.save(vote);
        return true;
    }


    public Vote findOne(Long id) {
        Vote vote = voteDao.findVoteWithSubject(id);
        return vote;
    }


    public String getQrcodeUrl(Long id) throws WxErrorException {
        Vote vote = this.findOne(id);
        Material material1 = vote.getMaterial();
        String url;
        if (material1 == null) {
            url = rootConst.getUrl() + "/baojie?id=" + vote.getId();
            String s = wechatService.getService().shortUrl(url);
            byte[] qrcode = QrcodeUtils.createQrcode(s, null);
            String path = rootConst.getPath() + "/qrcode";
            String fileName = String.valueOf(new Date().getTime()) + ".jpg";
            FileUtils.byte2File(qrcode, path, fileName);
            Material material = new Material(path, fileName);
            materialService.save(material);
            material.setUrl(rootConst.getUrl() + File.separator + "material" + File.separator + "download" + File.separator + material.getId());
            materialService.save(material);
            vote.setMaterial(material);
            this.save(vote);
        } else {
            url = material1.getUrl();
        }
        return url;
    }

    public synchronized void vote(Set<Option> options, HttpSession session) throws WxErrorException {
        //查找粉丝
        if (session.getAttribute(SessionConsts.OPEN_ID) == null || session.getAttribute(SessionConsts.VOTE_ID) == null)
            return;
        Long voteId = Long.valueOf(String.valueOf(session.getAttribute(SessionConsts.VOTE_ID)));
        String openId = (String) session.getAttribute(SessionConsts.OPEN_ID);
        Follower follower = followerService.sysncFollower(openId);
        //是否投过票了
        Exchange exchange = exchangeDao.findByFollowerIdAndVoteId(follower.getId(), voteId);
        if (exchange == null) {
            //未投票
            // 投票
            exchange = new Exchange(follower.getId(), Long.valueOf(String.valueOf(session.getAttribute(SessionConsts.VOTE_ID))));
            exchangeDao.save(exchange);
            for (Option option : options) {
                FollowerOption followerOption = new FollowerOption(follower, option, option.getDescription());
                followerOptionDao.save(followerOption);
            }
        } else {
            //投过票
        }

        //是否抽过奖了
        if (exchange.getHasExchange()) {
            //已抽过奖
        } else {
            //抽奖
            Vote vote = voteDao.findOneWithPrize(voteId);
            for (Prize prize : vote.getPrizes()) {
                //没有剩余了
                if (prize.getExchanged() >= prize.getTotal()) continue;
                Integer risk = prize.getRisk();
                if (risk == null) continue;
                int random = RandomUtil.nextInt(1, 100);
                if (random < risk) {
                    prize.setExchanged(prize.getExchanged() + 1);
                    prizeService.save(prize);
                    //中奖了
                    exchange.setHasPrize(true);
                    exchange.setPrizeId(prize.getId());
                    exchange.setCode(RandomUtil.nextInt(1, 999999));
                    break;
                }
            }
            exchange.setHasExchange(true);
            exchangeDao.save(exchange);
        }

    }

    public List<Vote> list() {
        List<Vote> all = voteDao.findAll();
        return all;
    }
}
